// 将api方法引入到store中 在actions中调用  在actions中通过commit调用mutations中的方法 在组件中通过this.$store.dispatch('user/login', userInfo)调用actions中的方法 或者 this.$store.commit('user/SET_TOKEN', 'token')或者 this.$store.state.user.name或者 this.$store.getters.name或者 this.$store.getters.avatar或者 this.$store.dispatch('user/logout')
import { login, register, getInfo } from '@/api/user'// user api
import { getToken, setToken, removeToken } from '@/utils/auth'// token storage
import encrypt from '@/utils/encrypt'// encrypt加密
import { resetRouter } from '@/router'// resetRouter重置路由

const getDefaultState = () => { // 重置state数据
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: []
  }
}

const state = getDefaultState()// 初始化state

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())// 重置state
  },
  SET_TOKEN: (state, token) => { // 设置token
    state.token = token
  },
  SET_NAME: (state, name) => { // 设置name
    state.name = name
  },
  SET_AVATAR: (state, avatar) => { // 设置avatar
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => { // 设置roles
    state.roles = roles
  }
}

const actions = {
  // user login
  // 在 Vuex 中，commit 用于触发 mutation，而 async 关键字用于处理异步操作
  async login({ commit }, userInfo) { // 登录
    const { username, password } = userInfo// 解构赋值
    const encryptPwd = await encrypt(password)// 加密
    return new Promise((resolve, reject) => { // promise异步操作
      login({ username: username.trim(), password: encryptPwd })
        .then((response) => {
          const { data } = response // 解构赋值
          commit('SET_TOKEN', data.token) //  设置state.token
          setToken(data.token) // 设置token
          resolve() // 返回resolve
        })
        .catch((error) => { // 返回reject
          console.log('error: ', error) // 打印错误
          reject(error) // 返回reject
        })
    })
  },
  // register
  async register({ commit }, userInfo) {
    const { username, password, email } = userInfo // 解构赋值
    const encryptPwd = await encrypt(password) // 加密
    return new Promise((resolve, reject) => { // promise异步操作
      register({ username: username.trim(), password: encryptPwd, email: email.trim() })// 调用api
        .then((response) => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
        })
        .catch((error) => {
          console.log('error: ', error)
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then((response) => {
          const { data } = response // 解构赋值
          if (!data) { // 未登录
            reject('Verification failed, please Login again.')
          }

          const { roles, username, avatar } = data // 解构赋值

          // roles must be a non-empty array
          if (!roles || roles.length <= 0) { // 未登录
            reject('getInfo: roles must be a non-null array!')
          }

          commit('SET_ROLES', roles) // 设置state.roles
          commit('SET_NAME', username) // 设置state.name
          commit('SET_AVATAR', process.env.VUE_APP_BASE_API + avatar) // 设置state.avatar
          resolve(data) // 返回resolve data
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // user logout  退出登录
  logout({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      resetRouter() // 重置路由
      commit('RESET_STATE') // 重置state
      resolve() // 返回resolve
    })
  },

  // remove token
  resetToken({ commit }) { // 重置token
    return new Promise((resolve) => { // promise异步操作
      removeToken() // must remove  token  first
      commit('RESET_STATE') // 重置state
      resolve() // 返回resolve
    })
  }
}

export default {
  namespaced: true, // 命名空间
  state, // state
  mutations, // mutations
  actions // actions
}
